package com.tg.app.view;

import static com.tg.app.activity.device.CameraViewActivity.PLAY_MODE_REALTIME;
import static com.tg.app.activity.device.CameraViewActivity.ZOOM_INIT;
import static com.tg.app.view.CameraPlayerStatusView.STATUS_ERROR_PLAY_END;
import static com.tg.app.view.CameraPlayerStatusView.STATUS_ERROR_TIME_DATA_NONE;
import static com.tg.app.view.CameraPlayerStatusView.STATUS_LOADING;
import static com.tg.app.view.CameraPlayerStatusView.STATUS_NONE;
import static com.tg.app.view.CameraPlayerView.PLAYER_ID_MINI;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.text.HtmlCompat;

import com.alibaba.fastjson.JSON;
import com.appbase.custom.constant.CommonConstants;
import com.appbase.custom.constant.LensesConstants;
import com.appbase.custom.constant.RecordModeConstants;
import com.hjq.permissions.Permission;
import com.demo.view.PlayerTopInfoView;
import com.demo.view.SolarBatteryView;
import com.demo.view.TGFocusingView;
import com.tange.base.toolkit.AppUtil;
import com.tange.base.toolkit.DateUtil;
import com.tange.base.toolkit.PreferenceUtil;
import com.tange.base.toolkit.StringUtils;
import com.tange.base.toolkit.TGThreadPool;
import com.tange.module.device.feature.DeviceFeature;
import com.tg.app.R;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.helper.AppHelper;
import com.tg.app.helper.CameraViewHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.helper.DeviceHelper;
import com.tg.app.helper.DeviceModelHelper;
import com.tg.app.helper.DeviceUIHelper;
import com.tg.app.listener.OnCameraZoomListener;
import com.tg.app.listener.OnPlayerForeSightListener;
import com.tg.app.listener.OnZoomViewListener;
import com.tg.app.util.LocalThumbnailUtils;
import com.tg.app.util.LogUtils;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.app.widget.PtzControlView;
import com.tg.app.widget.ZoomView;
import com.tg.appcommon.android.AbImageUtil;
import com.tange.base.toolkit.DimenUtil;
import com.tg.appcommon.android.ImageUtils;
import com.tg.appcommon.android.PermissionUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.data.bean.DeviceItem;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.bean.DeviceSettingsInfo_;
import com.tg.data.helper.DeviceItemHelper;
import com.tg.data.helper.DeviceTypeHelper;
import com.tg.data.http.entity.AVFrames;
import com.tg.data.http.entity.DeviceModelBean;
import com.tg.data.http.entity.WatchTime;
import com.tg.data.media.AudioDecoder;
import com.tg.data.media.DefaultVideoDecoder;
import com.tg.data.media.OnMediaFormatChangedListener;
import com.tg.data.media.OnMediaPlayListener;
import com.tg.data.media.OnScreencapListener;
import com.tg.data.media.VideoDecoder;
import com.tg.data.media.VideoFileRecorder;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import io.objectbox.Box;


public class ACCameraPlayerView extends LinearLayout implements View.OnClickListener {
    private static final String TAG = "ACCameraPlayerView";
    public static final int MAGE_1080P_W = 1920;
    public static final int MAGE_1080P_H = 1080;
    private ImageView thumbnailImage;
    private Context mContext;
    private LinearLayout recordTimeLayout, thumbnailLayout;
    private TextView networkStatusTv;
    private TextView recordTimeText, zoomText, playbackTimeText,watchTimeText;
    private ACCameraPlayerViewClickListener playerViewClickListener;
    private ZoomView mZoomView;
    private TextView mZoomTextView;
    private float zoomPos;
    private float zoomPos2;
    private int mResolution;
    private int cameraType;
    private int lensesType;

    private OnZoomViewListener onZoomViewListener;
    private DeviceFeature deviceFeature;
    private boolean isSwapScreen = false;
    private boolean isMuteOn;
    private boolean isStatusBar;
    private DeviceModelBean deviceModelBean;


    private OnMediaPlayListener onMediaPlayListener;
    private OnScreencapListener onScreencapListener;
    private OnMediaFormatChangedListener formatChangedListener;
    public boolean mResetPlayer = false;
    public boolean isResolutionHide = false;
    private RadioGroup mLensesGroup;
    private RadioButton mLensesFar, mLensesNear;
    private CameraBatteryStatusView mBatteryStatusLayout;
    private SolarBatteryView mSolarBatteryView;
    private DeviceItem mDevice;
    private boolean isUpdateViewSizeEnable = true;
    private CameraPlayerToolbarView toolbarView;
    private CameraPlayerPtzView ptzView;
    private CameraPlayerStatusView relStatusLayout;
    private CameraPlayerView playerView;
    private ConstraintLayout rootView;
    private OnCameraZoomListener onCameraZoomListener;
    private boolean isLiveViewShow = true;
    private OnZoomViewListener onMainZoomViewListener;
    private View mFloatView,mPlayBackTimeLine;

    private TGFocusingView mFocusingView;

    private String bitrateStr = "";
    private String signalLevelStr = "";
    private CameraPlayerPlayBackControlView playBackControlView;
    private CameraPlayerPlayBackControlView.OnControlClickListener onControlClickListener;
    private boolean isPlaybackPause = false;
    private boolean isToolbarhide = true;
    public DeviceSettingsInfo mDeviceSettingsInfo;

    private PlayerTopInfoView playerTopInfoView;
    private boolean isPlaybackRunning = false;
    private OnPlayerForeSightListener onPlayerForeSightListener;
    private SimServicePayBanner simServicePayBanner;
    private int mUserId = 0;

    public int getCurPlayerHeight(){
        if (playerView != null){
            return playerView.getCurPlayerHeight();
        }
        return 0;
    }

    public void setCameraViewSize(int height) {
        if (playerView != null){
            playerView.setCameraViewSize(height);
        }
    }

    public void updateCameraViewSize(){
        TGThreadPool.executeOnUiThread(() -> {
            if (playerView != null){
                setUpdateViewSize(true);
                int h = playerView.updateCameraViewSize();
                if (h >0){
                   if (playerViewClickListener != null){
                       playerViewClickListener.onAdjustHeight();
                   }
                }

            }
        });

    }

    public void setDeviceModelBean(DeviceModelBean deviceModelBean){
        this.deviceModelBean = deviceModelBean;
    }
    public void setPlaybackRunning(boolean running){
        this.isPlaybackRunning = running;
        playerTopInfoView.setVisibility(running? View.GONE : View.VISIBLE);
    }
    public void setOnPlayerForeSightListener(OnPlayerForeSightListener onPlayerForeSightListener) {
        this.onPlayerForeSightListener = onPlayerForeSightListener;
    }

    public void setOnControlClickListener(CameraPlayerPlayBackControlView.OnControlClickListener onControlClickListener) {
        this.onControlClickListener = onControlClickListener;
    }

    public void setFloatView(View floatView) {
        this.mFloatView = floatView;
    }

    public void setUpdateViewSize(boolean update) {
        isUpdateViewSizeEnable = update;
        if (playerView != null) {
            playerView.setUpdateViewSizeEnable(isUpdateViewSizeEnable);
        }
    }

    public void showLockDellImageIcon(){
       if (toolbarView != null){
           toolbarView.showLockDellImageIcon();
           toolbarView.showMute(deviceFeature != null && deviceFeature.supportMicrophone);
       }
    }

    public void setResolutionHide(boolean isResolutionHide) {
        this.isResolutionHide = isResolutionHide;
    }

    public void setDeviceUIHelper(DeviceUIHelper deviceUIHelper) {
        mDeviceUIHelper = deviceUIHelper;
        relStatusLayout.setDeviceUIHelper(mDeviceUIHelper);
        toolbarView.setDeviceUIHelper(mDeviceUIHelper);
    }

    private DeviceUIHelper mDeviceUIHelper;


    public void setDeviceItem(DeviceItem device) {
        this.mDevice = device;
        if (relStatusLayout != null) {
            relStatusLayout.setDeviceItem(device);
        }
        this.isSwapScreen = isSwap();
        initDeviceInfo();
    }


    public void setOnScreencapListener(OnScreencapListener onScreencapListener) {
        this.onScreencapListener = onScreencapListener;
        updateListener();
    }

    public void setFormatChangedListener(OnMediaFormatChangedListener formatChangedListener) {
        this.formatChangedListener = formatChangedListener;
        updateListener();
    }

    public void setOnMediaPlayListener(OnMediaPlayListener onMediaPlayListener) {
        this.onMediaPlayListener = onMediaPlayListener;
        updateListener();
    }

    private PtzControlView.OnPtzControlTouchListener ptzControlTouchListener;

    public void setOnZoomViewListener(OnZoomViewListener onZoomViewListener) {
        this.onZoomViewListener = onZoomViewListener;
    }

    public ACCameraPlayerView(Context context) {
        super(context, null);
    }

    public VideoDecoder getMediaSync() {
        if (playerView != null) {
            return playerView.getMediaSync();
        }
        return null;
    }

    public CameraPlayerView getPlayerView() {
        return playerView;
    }

    public void mediaSyncStart() {
        if (playerView != null) {
            playerView.mediaSyncStart();
        }

    }

    public void mediaSyncPause() {
        isPlaybackPause = false;
        if (playerView != null) {
            playerView.mediaSyncClear();
        }
    }

    public ACCameraPlayerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ACCameraPlayerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void setPlayerViewClickListener(ACCameraPlayerViewClickListener playerViewClickListener) {
        this.playerViewClickListener = playerViewClickListener;
        relStatusLayout.setPlayerViewClickListener(playerViewClickListener);
    }

    public void setOnPtzControlTouchListener(PtzControlView.OnPtzControlTouchListener ptzControlTouchListener) {
        this.ptzControlTouchListener = ptzControlTouchListener;
        updateListener();
    }

    private void init(Context context) {
        mContext = context;
        View view = LayoutInflater.from(context).inflate(R.layout.layout_camera_player_view, this);
        rootView = view.findViewById(R.id.player_view);
        addPlayerView();
        initView(view);
        setListener();
        int barH = DimenUtil.dp2px(context, 60);
        int zoomW = DimenUtil.dp2px(context, 40);
        toolbarView.animate().translationY(barH).start();
        int ld = getLayoutDirection();
        if (ld == View.LAYOUT_DIRECTION_RTL) {
            zoomW = -zoomW;
        }
        mZoomView.animate().translationX(zoomW).start();
        mFocusingView.animate().translationX(-zoomW).start();
        mUserId = PreferenceUtil.getInt(getContext(), CommonConstants.PRE_USER_ID);
    }

    private void addPlayerView() {
        ConstraintLayout.LayoutParams layoutParams = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_CONSTRAINT, ConstraintLayout.LayoutParams.MATCH_CONSTRAINT);
        layoutParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        layoutParams.topToTop = ConstraintLayout.LayoutParams.PARENT_ID;
        String uuid = (String) TGApplicationBase.getInstance().getGlobalObject(CameraPlayerSingleView.CUR_DEVICE_UUID);
        if (!StringUtils.isEmpty(uuid)){
            DeviceFeature deviceFeature = (DeviceFeature) TGApplicationBase.getInstance().getGlobalObject(CameraPlayerSingleView.CUR_DEVICE_FEATURE);
            if (DeviceFeatureHelper.supportMultiChannels(deviceFeature) && StringUtils.equalsIgnoreCase(uuid, deviceFeature.uuid)){
                TGLog.d(TAG, "addPlayerView addPlayerView");
                this.isSwapScreen = isSwap(uuid);
                CameraPlayerPiPVerticalView pVerticalView = createVerticalView();
                pVerticalView.setOpenOverlap(false);
                pVerticalView.setOnCameraPlayerListener(viewId -> {
                    setLensesChanged(viewId == PLAYER_ID_MINI);
                });

                pVerticalView.setForeSightEnable(deviceFeature.supportLocInPic);
                pVerticalView.setForeSightSubEnable(deviceFeature.supportLocInPic2);
                pVerticalView.setOnSwitchPlayerListener(this::switchPlayer);
                playerView = pVerticalView;
                TGLog.d(ZoomView.TAG, "addPlayerView pVerticalView");
                playerView.setAnchorView(rootView);
                rootView.addView(playerView, 0, layoutParams);
                if (mFloatView != null){
                    playerView.setFloatView(mFloatView);
                }
                return;
            }
        }
        playerView = new CameraPlayerSingleView(mContext);
        TGLog.d(TAG, "addPlayerView CameraPlayerSingleView");
        rootView.addView(playerView, 0, layoutParams);
    }


    private boolean hasBattery(){
        return deviceFeature != null && deviceFeature.isBatteryCam || DeviceHelper.isBatteryDevice(mDevice);
    }

    private boolean isShowVideoRecordingFromPreference(){
        if (mDevice != null && mDevice.isShare()){
            return true;
        }

        boolean isContains = PreferenceUtil.contains(getContext(), CommonConstants.PRE_SETTINGS_VIDEO_UUID + getUuid() + mUserId);
        if (!isContains){
            return DeviceHelper.isShowRecord(mDevice, mDeviceSettingsInfo);
        }

        return PreferenceUtil.getBoolean(getContext(), CommonConstants.PRE_SETTINGS_VIDEO_UUID + getUuid() + mUserId);
    }

    private boolean showVideoRecording(){
        boolean show = isShowVideoRecordingFromPreference();
        if (!show){
            return false;
        }
        byte recordFun = DeviceFeatureHelper.getRecordFun(deviceFeature);
        if (recordFun == 2){
            return true;
        }

        if (recordFun == 1){
            return false;
        }

        return mDeviceSettingsInfo != null && mDeviceSettingsInfo.total > 0 && mDeviceSettingsInfo.recordType == RecordModeConstants.RECORD_MODE_FULLTIME && !DeviceFeatureHelper.isNoMedia(deviceFeature);
    }

    private String getUuid(){
        String uuid = mDevice ==  null? "" : mDevice.uuid;
        if (StringUtils.isEmpty(uuid)){
            uuid = mDeviceSettingsInfo == null? "" : mDeviceSettingsInfo.uuid;
        }
        return uuid;
    }

    private boolean showBattery(){
        boolean show = PreferenceUtil.contains(getContext(),  CommonConstants.PRE_SETTINGS_BATTERY_UUID + getUuid() + mUserId);
        if (!show){
            show = true;
        }else{
            show =  PreferenceUtil.getBoolean(getContext(), CommonConstants.PRE_SETTINGS_BATTERY_UUID + getUuid() + mUserId);
        }
        return show;
    }

    public int getCurrentPlayer() {
        return playerView == null? 0 : playerView.currentPlayer;
    }

    @SuppressLint("SetTextI18n")
    public void initDeviceInfo(){
        if (mDevice != null) {
            Box<DeviceSettingsInfo> deviceSettingsInfoBox = ObjectBoxUtil.getDeviceSettingsInfo();
            if (deviceSettingsInfoBox != null){
                mDeviceSettingsInfo = deviceSettingsInfoBox.query().equal(DeviceSettingsInfo_.uuid, mDevice.uuid).build().findFirst();
                if (mDeviceSettingsInfo != null){
                    setResolution(playerView.getCurrentPlayer() == 0? mDeviceSettingsInfo.quality : mDeviceSettingsInfo.quality2);
                }
            }

        }
        mUserId = PreferenceUtil.getInt(getContext(), CommonConstants.PRE_USER_ID);
        boolean show = showVideoRecording();
        TGLog.d("VideoType","showVideoRecording 12 = " + show);
        playerTopInfoView.getRecording().setVisibility(show? View.VISIBLE : View.GONE);
        String uuid = mDeviceSettingsInfo != null? mDeviceSettingsInfo.uuid : "";
        if (StringUtils.isEmpty(uuid)){
            uuid = mDevice != null? mDevice.uuid : "";
        }
        playerTopInfoView.showUI(uuid, true);
        playerTopInfoView.showView(uuid, true);
        mSolarBatteryView.setVisibility(GONE);
        setFocusViewListener();
    }

    public void hidePlayTopInfoView(String uuid){
        playerTopInfoView.showView(uuid, false);
    }

    private TGFocusingView.OnFocusTouchListener onFocusTouchListener;
    public void setFocusTouchListener(TGFocusingView.OnFocusTouchListener onFocusTouchListener){
        this.onFocusTouchListener = onFocusTouchListener;
    }
    private void setFocusViewListener(){
        mFocusingView.setFocusTouchListener(new TGFocusingView.OnFocusTouchListener() {
            @Override
            public void onShortCmd(int control) {
                if (onFocusTouchListener != null){
                    onFocusTouchListener.onShortCmd(control);
                }
            }

            @Override
            public void onStopCmd() {
                if (onFocusTouchListener != null){
                    onFocusTouchListener.onStopCmd();
                }
            }

            @Override
            public void onLongCmd(int control) {
                if (onFocusTouchListener != null){
                    onFocusTouchListener.onLongCmd(control);
                }
            }

            @Override
            public void onTouch(boolean up, boolean add) {
                if (onFocusTouchListener != null){
                    onFocusTouchListener.onTouch(up, add);
                }
            }
        });
    }

    private void initView(View view) {

        toolbarView = view.findViewById(R.id.rel_camera_player_toolbar);

        recordTimeLayout = view.findViewById(R.id.ll_camera_player_record_time);
        recordTimeText = view.findViewById(R.id.tv_camera_player_record_time);
        mZoomView = view.findViewById(R.id.camera_player_zoomview);
        mFocusingView = view.findViewById(R.id.camera_player_focus);

        mZoomTextView = view.findViewById(R.id.tv_zoom);
        relStatusLayout = view.findViewById(R.id.camera_player_status);

        zoomText = view.findViewById(R.id.tv_camera_player_view_zoom);
        thumbnailImage = view.findViewById(R.id.iv_camera_player_thumbnail);
        thumbnailLayout = view.findViewById(R.id.ll_camera_player_thumbnail);
        playbackTimeText = view.findViewById(R.id.tv_camera_player_playback_time);

        mLensesGroup = view.findViewById(R.id.rg_camera_lenses);
        mLensesFar = view.findViewById(R.id.rb_lenses_far);
        mLensesNear = view.findViewById(R.id.rb_lenses_near);
        mBatteryStatusLayout = view.findViewById(R.id.camera_player_battery_status_laytout);
        mSolarBatteryView =view.findViewById(R.id.camera_player_solar_battery);
        ptzView = view.findViewById(R.id.camera_player_ptz);
        mPlayBackTimeLine = view.findViewById(R.id.ll_camera_player_playback_timeline);
        watchTimeText =view.findViewById(R.id.tv_camera_player_watch_time);
        playBackControlView = view.findViewById(R.id.camera_player_playback_control);
        playerTopInfoView = view.findViewById(R.id.camera_player_top_info);
        simServicePayBanner =view.findViewById(R.id.sim_banner);
        initDeviceInfo();
    }

    public void setWatchTime(WatchTime watchTime){
        TGThreadPool.executeOnUiThread(() -> {
            if (watchTime==null){
                watchTimeText.setVisibility(GONE);
                return;
            }
            int time = watchTime.getTotal()- watchTime.getUsed();
            watchTimeText.setVisibility(time==0 ?GONE:VISIBLE);
            int m = (int) Math.ceil(time/60.0f);
            String unit = getResources().getString(R.string.car_watch_times);
            if (m==1){
                unit =  getResources().getString(R.string.car_watch_time);;
            }
            String content = String.format(unit,m);
            Spanned spanned = HtmlCompat.fromHtml(content,HtmlCompat.FROM_HTML_MODE_LEGACY);
            watchTimeText.setText(spanned);
        });

    }
    public void setPlaybackTimeText(String timeText) {
        this.playbackTimeText.setText(timeText);
    }

    public void setPlaybackTimeVisiable(int visiable) {
        this.playbackTimeText.setVisibility(visiable);
    }

    public void setLensesChanged() {
        if (canSetLensesGroup()) {
            if (mLensesGroup.getCheckedRadioButtonId() == R.id.rb_lenses_far) {
                mLensesNear.setChecked(true);
            } else {
                mLensesFar.setChecked(true);
            }
        }
    }

    public void setLensesChanged(boolean isFar) {
        if (canSetLensesGroup()) {
            if (isFar) {
                mLensesFar.setChecked(true);
            } else {
                mLensesNear.setChecked(true);
            }
        }
    }

    public void setZoomTextView(String text, int index) {
        boolean supportMultiChannels = DeviceFeatureHelper.supportMultiChannels(deviceFeature) && playerView instanceof CameraPlayerPiPVerticalView;
        TGLog.d("supportMultiChannels = " + supportMultiChannels + ", index = " + index);
        if (supportMultiChannels){
            mZoomTextView.setVisibility(GONE);
            ((CameraPlayerPiPVerticalView)playerView).setZoomTextView(text, index);
        }else{
            mZoomTextView.setVisibility(VISIBLE);
            mZoomTextView.setText(text);
        }
    }

    public void hideZoomTextView(int index) {
        mZoomTextView.setVisibility(GONE);
        boolean supportMultiChannels = DeviceFeatureHelper.supportMultiChannels(deviceFeature) && playerView instanceof CameraPlayerPiPVerticalView;
        TGLog.d("supportMultiChannels = " + supportMultiChannels + ", index = " + index);
        if (supportMultiChannels){
            ((CameraPlayerPiPVerticalView)playerView).hideZoomTextView(index);
        }
    }


    public void setZoomHidden() {
        zoomText.setVisibility(GONE);
    }

    public void ptzDirectionHide() {
        ptzView.hide();
    }

    public void ptzDirection(int control, boolean small) {
        ptzView.direction(control, small);
    }

    @SuppressLint({"DefaultLocale", "SetTextI18n"})
    public void updateBitrate(float bitrate) {
        bitrateStr = StringUtils.getBitrateString(bitrate);
        updateStatusText(-1);
    }

    public void updateFrameRate(int frame){
        TGThreadPool.executeOnUiThread(() -> playerTopInfoView.setFrameRate(ResourcesUtil.getString(R.string.setting_frame_rate) + frame));
    }

    public void showPlayerTopInfoView(boolean show){
        playerTopInfoView.setVisibility(show? VISIBLE : GONE);
    }

    private void updateStatusText(int level) {
        TGThreadPool.executeOnUiThread(() -> {
            if (!StringUtils.isEmpty(bitrateStr)){
                playerTopInfoView.getSpeedView().setText(bitrateStr);
            }
            if (level != -1){
                playerTopInfoView.getSignalView().setText("");
                DeviceHelper.setSignalImage(mDevice, playerTopInfoView.getSignalView(), level);
            }
           if (playerView != null){
               playerView.prinfInfo();
           }
            TGLog.d("ACCameraPlayerView", "signalLevelStr = " + signalLevelStr);
        });
    }

    public void setPlayerViewSizePortrait() {
        TGLog.d(TAG, "setPlayerViewSizePortrait");
        setUpdateViewSize(true);
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setZoomHidden();
        }
    }

    public void updateBatteryImageStatus(int battery, int mode, int batteryLow) {
        boolean show = DeviceHelper.isSolar(mDevice);
        TGLog.d("=== getDeviceStatusInfo updateBatteryImageStatus show = " + show + ", mode = " + mode + ", batteryLow = " + batteryLow + ", battery= " + battery);
        showBatteryImage();
        show = showBattery() && hasBattery();
        playerTopInfoView.showBattery(show);
        if (show){
            playerTopInfoView.setBattery(battery, mode);
        }
    }

    public void showBatteryImage(){
        mBatteryStatusLayout.setVisibility(GONE);
    }

    public void updateBatteryTextStatus(int battery, int mode) {
        TGThreadPool.executeOnUiThread(() -> playerTopInfoView.setBattery(battery, mode));

    }

    @SuppressLint("SetTextI18n")
    public void updateSignalLevel(int type, int level) {
        signalLevelStr = getResources().getString(R.string.camera_player_signal_level) + level + "%";
        updateStatusText(level);
//        //0:有线;1-Wifi;2-4G
//        if (type != 1 && type != 2) {
//            signalLevelText.setVisibility(VISIBLE);
//        }
    }

    public int getCameraType() {
        return cameraType;
    }

    public void setCameraType(int cameraType) {
        this.cameraType = cameraType;
        TGLog.i(TAG, "setCameraType " + cameraType);
        if (isLiveVideoPlay()) {
            isPlaybackPause  = false;
            toolbarView.setScreenCapEnable();
            playBackControlView.setVisibility(GONE);
            toolbarView.setSpeedVisibility(false);
            TGLog.i(TAG, "isResolutionHide");
            toolbarView.setResolutionVisibility(!isResolutionHide);


            if (deviceFeature != null) {
                if (deviceFeature.supportZoom && toolbarView.getVisibility() == VISIBLE) {
                    setZoomView(VISIBLE);
                }

                if (DeviceFeatureHelper.supportFocus(deviceFeature)){
                    setFocusingView(VISIBLE, false);
                }
            }

        } else {
            toolbarView.setSpeedVisibility(true);
            toolbarView.setResolutionVisibility(false);
            setZoomView(GONE);
            setFocusingView(GONE, false);
            setLensesView(GONE);
        }
        setMedidaType();
        setSimServicePayBannerShow();
    }

    public void setSpeedVisibility(boolean visible) {
        toolbarView.setSpeedVisibility(visible);
    }

    private boolean isLiveVideoPlay() {
        return this.cameraType == CommonConstants.CAMERA_TYPE_LIVE;
    }

    public void setZoomView(int visible) {
        setZoomViewEx(visible, false);
    }

    private void setZoomViewEx(int visible, boolean nowVisible) {
        TGLog.d(ZoomView.TAG, "setZoomView visible = " + visible + ", newVisible = " + nowVisible + ", mDeviceUIHelper.getPlaybackDisplay()" + mDeviceUIHelper.getPlaybackDisplay() + ", getResources().getConfiguration().orientation = " + getResources().getConfiguration().orientation);
        int ld = getLayoutDirection();
        if (visible == View.VISIBLE) {
            if (mDeviceUIHelper.getPlaybackDisplay() != PLAY_MODE_REALTIME){
                mZoomView.setVisibility(GONE);
            }else {
                if (nowVisible && (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
                    mZoomView.setVisibility(DeviceFeatureHelper.supportMultiChannels(deviceFeature)? View.GONE : View.VISIBLE);
                }
                mZoomView.animate().translationX(0).setDuration(240).setListener(null).start();
                if (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    mZoomView.setVisibility(DeviceFeatureHelper.supportMultiChannels(deviceFeature)? View.GONE : View.VISIBLE);
                }
            }

        } else {
            int zoomW = DimenUtil.dp2px(mContext, 80);
            if (ld == View.LAYOUT_DIRECTION_RTL) {
                zoomW = -zoomW;
            }
            if (nowVisible) {
                mZoomView.setVisibility(View.GONE);
            }
            mZoomView.animate().translationX(zoomW).setDuration(240).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    HideZoomView(mZoomView, mZoomTextView);
                }
            }).start();
        }

        if (DeviceFeatureHelper.supportMultiChannels(deviceFeature) && playerView instanceof CameraPlayerPiPVerticalView) {
            ((CameraPlayerPiPVerticalView)playerView).setZoomView(visible);
        }
    }


    public void setFocusingView(int visible, boolean nowVisible) {
        TGLog.d(ZoomView.TAG, "setFocusingView visible = " + visible + ", newVisible = " + nowVisible + ", mDeviceUIHelper.getPlaybackDisplay()" + mDeviceUIHelper.getPlaybackDisplay() + ", getResources().getConfiguration().orientation = " + getResources().getConfiguration().orientation);
        int ld = getLayoutDirection();
        if (visible == View.VISIBLE) {
            if (mDeviceUIHelper.getPlaybackDisplay() != PLAY_MODE_REALTIME){
                mFocusingView.setVisibility(GONE);
            }else {
                if (nowVisible && (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)) {
                    mFocusingView.setVisibility(DeviceFeatureHelper.supportFocus(deviceFeature)? View.VISIBLE : View.GONE);
                }
                mFocusingView.animate().translationX(0).setDuration(240).setListener(null).start();
                if (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                    mFocusingView.setVisibility(DeviceFeatureHelper.supportFocus(deviceFeature)? View.VISIBLE : View.GONE);
                }
            }

        } else {
            int zoomW = DimenUtil.dp2px(mContext, 80);
            if (ld == View.LAYOUT_DIRECTION_RTL) {
                zoomW = -zoomW;
            }
            if (nowVisible) {
                mFocusingView.setVisibility(View.GONE);
            }

            mFocusingView.animate().translationX(-zoomW).setDuration(240).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mFocusingView.setVisibility(View.GONE);
                }
            }).start();
        }
    }
    
    private void HideZoomView(LinearLayout zoomView, TextView zoomTextView) {
        zoomView.setVisibility(View.GONE);
        zoomTextView.setVisibility(GONE);
    }

    private void setLensesView(int visible) {
        if (visible == View.VISIBLE) {
            mLensesGroup.animate().translationX(0).setDuration(240).setListener(null).start();
            mLensesGroup.setVisibility(View.VISIBLE);
        } else {
            int w = DimenUtil.dp2px(mContext, 40);
            mLensesGroup.animate().translationX(-mLensesGroup.getWidth() - w).setDuration(240).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    mLensesGroup.setVisibility(View.GONE);
                }
            }).start();
        }
    }

    public void resetPlayerLocation() {
        if (playerView != null) {
            playerView.resetPlayerLocation();
        }
    }

    public void setBackgroud() {
        if (playerView != null) {
            playerView.setBackgroud();
        }
    }


    public void audioSyncPts(long pts) {
        if (playerView != null) {
            playerView.setVideoSyncPts(pts);
        }
    }

    public int getLoadingVisibility() {
        return relStatusLayout.getLoadingVisibility();
    }

    public void setLoadingVisibility(int visible) {
        setLoadingVisibility(visible, null);
    }

    public void setLoadingVisibility(int visible, String text) {
        mPlayBackTimeLine.setVisibility(GONE);
        relStatusLayout.setLoadingVisibility(visible, text);
        if (visible == VISIBLE) {
            playBackControlView.setVisibility(GONE);
            if (!DeviceFeatureHelper.supportMultiChannels(deviceFeature)) {
                setToolbarVisibility(GONE);
            }
            ptzDirectionHide();
            setWatchTime(null);
        }
    }

    private boolean canSetLensesGroup() {
        return isLiveVideoPlay() && deviceFeature.support2Lenses;
    }

    public void setToolbarVisibility(int visible) {
        if (toolbarView.getVisibility() != visible) {
            setToolbarVisibilityImpl(visible);
        }
    }

    public void hidePlayBackCtlView(){
        playBackControlView.setVisibility(GONE);
    }

    public void setToolbarVisibilityImpl(int visible) {
        if (isLiveVideoPlay()) {
            if (deviceFeature != null) {
                if (deviceFeature.supportZoom) {
                    setZoomView(visible);
                }
                if (deviceFeature.mfocus) {
                    setFocusingView(visible, false);
                }
                if (DeviceFeatureHelper.supportMultiChannels(deviceFeature)) {
                    setLensesView(GONE);
                } else {
                    if (deviceFeature.support2Lenses && !deviceFeature.noShortcut) {
                        setLensesView(visible);
                    }
                }
            }
        } else {
            setZoomView(GONE);
            setFocusingView(GONE, false);
            setLensesView(GONE);
        }

        if (visible == View.VISIBLE) {
            mPlayBackTimeLine.setVisibility(GONE);
            isToolbarhide = false;
            if (DeviceFeatureHelper.supportMultiChannels(deviceFeature) && playerView instanceof CameraPlayerPiPVerticalView){
                setResolution();

            }
            toolbarView.animateShow();
            if (!isLiveVideoPlay()){
                showPlaybackControl();
            }
            playerView.anchorViewShow();
        } else {
            toolbarHide();
        }
    }

    private void setResolution() {
        Box<DeviceSettingsInfo> settingsInfoBox = ObjectBoxUtil.getDeviceSettingsInfo();
        if (settingsInfoBox != null) {
            String uuid = mDevice == null? "" : mDevice.uuid;
            if (StringUtils.isEmpty(uuid)){
                uuid = (String)TGApplicationBase.getInstance().getGlobalObject(CameraPlayerSingleView.CUR_DEVICE_UUID);
            }
            DeviceSettingsInfo deviceSettingsInfo = settingsInfoBox.query().equal(DeviceSettingsInfo_.uuid, uuid).build().findFirst();
            if (deviceSettingsInfo !=  null){
                setResolution(playerView.getCurrentPlayer() == 0? deviceSettingsInfo.quality : deviceSettingsInfo.quality2);
            }

        }
    }

    private void toolbarHide(){
        isToolbarhide = true;
        toolbarView.animateHide();
        playBackControlView.setVisibility(GONE);
        playerView.anchorViewHide();
        setWatchTime(null);
    }
    public int getToolbarVisibility() {
        return toolbarView.getVisibility();
    }

    private void setLensesType(float type) {
        lensesType = (int) type;
        if (deviceFeature == null || !deviceFeature.support2Lenses){
            return;
        }
        if (is2LensesCapZoomFar()) {
            lensesType = 1;
        }
        if (!deviceFeature.supportMultiChannels){
            deviceFeature.currentPlayer = lensesType;
        }
        TGLog.d("type = " + lensesType + ", supportZoom = " + deviceFeature.supportZoom);
        if (deviceFeature.supportZoom) {
            if (mZoomView.isFar(lensesType)) {
                mLensesFar.setChecked(true);
                showPtzControl(LensesConstants.LENSES_MODE_FAR);
            } else {
                mLensesNear.setChecked(true);
                showPtzControl(LensesConstants.LENSES_MODE_NEAR);
            }

        } else {

            if (lensesType == 0) {
                mLensesNear.setChecked(true);
                showPtzControl(LensesConstants.LENSES_MODE_NEAR);
            } else {
                mLensesFar.setChecked(true);
                showPtzControl(LensesConstants.LENSES_MODE_FAR);
            }

        }
    }


    public int getPlayerStatus() {
        return relStatusLayout.getPlayerStatus();
    }

    public void setPlayerStatus(int status) {
        if (status!=STATUS_NONE||status!=STATUS_LOADING){
            toolbarHide();
            simServicePayBanner.setVisibility(GONE);
        }
        relStatusLayout.setPlayerStatus(status);
        if (isLandscape()&&(status==STATUS_ERROR_PLAY_END||status==STATUS_ERROR_TIME_DATA_NONE)){
            mPlayBackTimeLine.setVisibility(VISIBLE);
        }else {
            mPlayBackTimeLine.setVisibility(GONE);
        }
    }

    public void setErrorText(String text) {
        relStatusLayout.setErrorText(text);

    }

    public void setSendPTZCmd(boolean isSend) {
        if (playerView != null) {
            playerView.setSendPTZCmd(isSend);
        }
    }

    public void setSendFoucsCmd(boolean isSend) {
        if (mFocusingView != null) {
            mFocusingView.setSendFocusCmd(isSend);
        }
    }

    public void setMuteOn(boolean isMuteOn) {
        this.isMuteOn = isMuteOn;
        if (isMuteOn) {
            if (playerView != null) {
                playerView.audioSyncClear();
            }
        }
        toolbarView.seMute(isMuteOn);
    }
    public void setMuteEnable(boolean isMuteOn) {
        toolbarView.setMuteEnable(isMuteOn);
    }

    public void setLampMuteOn(boolean isMuteOn){
        if (playerView != null){
            playerView.setMuteOn(isMuteOn);
        }
    }

    private void setMedidaType() {
        int media = DefaultVideoDecoder.MEDIA_PLAY_TYPE_LIVE;
        if (cameraType == CommonConstants.CAMERA_TYPE_PLAYBACK_CLOUD) {
            media = DefaultVideoDecoder.MEDIA_PLAY_TYPE_CLOUD;
        } else if (cameraType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
            media = DefaultVideoDecoder.MEDIA_PLAY_TYPE_SDCARD;
        }
        if (playerView != null) {
            playerView.setMediaType(media);
        }

        if (media == DefaultVideoDecoder.MEDIA_PLAY_TYPE_SDCARD){
            playerView.setPipBtnVisibility(GONE);
        }
    }

    private void showPtzControl(int type) {
        boolean show = DeviceFeatureHelper.supportPTZ(deviceFeature, type == LensesConstants.LENSES_MODE_FAR ? 0 : 1);
        show = mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME && show;
        if (deviceFeature != null && deviceFeature.support2Lenses && !deviceFeature.supportMultiChannels) {
            if (AppUtil.isLandscape(getContext())) {
                if (show) {
                    playerView.setPtzControlTouchListener(ptzControlTouchListener);
                    toolbarView.supportPTZ();
                }else{
                    toolbarView.hidePTZ();
                }
            } else {
                playerView.setPtzControlTouchListener(show ? ptzControlTouchListener : null);
                toolbarView.hidePTZ();
            }
            if (!show) {
                playerView.setPtzControlTouchListener(null);
                toolbarView.hidePTZ();
            }
            if (playerViewClickListener != null) {
                playerViewClickListener.setPtzControlViewVisible(show);
            }
        } else if (deviceFeature != null && deviceFeature.supportMultiChannels) {
            playerView.setPtzControlTouchListener(show ? ptzControlTouchListener : null);
            if (show) {
                toolbarView.supportPTZ();
            } else {
                toolbarView.hidePTZ();
            }
        }
    }


    public void screenFullPlay() {
        if (playerView instanceof CameraPlayerPiPVerticalView){
            ((CameraPlayerPiPVerticalView)playerView).switchZoom(playerView.getCurrentPlayer());
        }
    }

    private void setListener() {

        onMainZoomViewListener = new OnZoomViewListener() {
            @Override
            public void onSingleClick(boolean show) {
                if (onZoomViewListener != null) {
                    onZoomViewListener.onSingleClick(show);
                }
            }

            @SuppressLint({"DefaultLocale", "SetTextI18n"})
            @Override
            public void onScale(float scale) {
                zoomText.setText(String.format("%.1f", scale) + "X");
                zoomText.setVisibility(View.VISIBLE);
                if (onZoomViewListener != null) {
                    onZoomViewListener.onScale(scale);
                }
            }
        };
        recordTimeLayout.setOnClickListener(this);
        relStatusLayout.setOnClickListener(this);
        mLensesGroup.setOnCheckedChangeListener((group, checkedId) -> {
            RadioButton far = group.findViewById(R.id.rb_lenses_far);
            RadioButton near = group.findViewById(R.id.rb_lenses_near);
            View view = mLensesGroup.findViewById(checkedId);
            if (checkedId == R.id.rb_lenses_far) {
                far.setBackgroundResource(R.drawable.btn_radio_far_near_checked_bg);
                far.setTextColor(getResources().getColor(R.color.far_near_btn_selected));
                near.setBackgroundResource(0);
                near.setTextColor(getResources().getColor(R.color.far_near_btn_not_selected));
                lensesType = LensesConstants.LENSES_MODE_FAR;
            } else {
                near.setBackgroundResource(R.drawable.btn_radio_far_near_checked_bg);
                near.setTextColor(getResources().getColor(R.color.far_near_btn_selected));
                far.setBackgroundResource(0);
                far.setTextColor(getResources().getColor(R.color.far_near_btn_not_selected));
                lensesType = LensesConstants.LENSES_MODE_NEAR;
            }
            TGLog.i(TAG, "setPrimaryView  " + (checkedId == R.id.rb_lenses_far ? 1 : 0));
            if (!DeviceFeatureHelper.supportMultiChannels(deviceFeature)) {
                if (deviceFeature != null){
                    deviceFeature.currentPlayer = lensesType;
                }
                showPtzControl(lensesType);
                playerViewClickListener.onLensesChanged(lensesType,view.isPressed());
            }

        });
        toolbarView.setToolbarViewClickListener(new CameraPlayerToolbarView.CameraPlayerToolbarViewClickListener() {
            @Override
            public void onMuteOnClick() {
                if (playerViewClickListener != null) {
                    playerViewClickListener.onMuteOnClick();
                }
            }

            @Override
            public void onResolutionChanged(View view) {
                resolutionChanged();
            }

            @Override
            public void onSpeedClick(View view) {
                if (recordTimeLayout.getVisibility() == VISIBLE) {
                    MsgCenterToast.show(getContext(), R.string.camera_player_screencap);
                } else {
                    List<String> list = getSpeed();
                    if (playerViewClickListener != null){
                        playerViewClickListener.onShowSpeed(list);
                        playerViewClickListener.onShowBar();
                    }
                }
            }

            @Override
            public void onScreenShotResult() {
                screenShotResult();
            }

            @Override
            public void onScreenFullClick() {

                if (playerViewClickListener != null) {
                    playerViewClickListener.onScreenFullClick();
                }

                screenFullPlay();
            }

            @Override
            public void onMicphoneLandClick() {

                setZoomViewEx(GONE, true);
                if (playerViewClickListener != null) {
                    playerViewClickListener.onMicphoneLandClick();
                    playerViewClickListener.onShowBar();
                }
            }

            @Override
            public void onScreenCapClick() {
                screenCapClick();
            }

            @Override
            public void onPtzControlClick() {
                if (playerViewClickListener != null) {
                    playerViewClickListener.onPtzControlClick();
                    playerViewClickListener.onShowBar();
                }

                setZoomViewEx(GONE, true);
            }

            @Override
            public void onPlayBackControlClick() {
                if (playerViewClickListener != null){
                    playerViewClickListener.onPlayBackControlClick();
                }

                setZoomViewEx(GONE, true);
            }
        });
        mPlayBackTimeLine.setOnClickListener(v -> {
            if (playerViewClickListener != null) {
                playerViewClickListener.onPlayBackControlClick();
            }
        });
        playBackControlView.setClickListener(pause -> {

            if (recordTimeLayout.getVisibility() == VISIBLE) {
                MsgCenterToast.show(getContext(), R.string.camera_player_screencap);
                return;
            }
            TGLog.i(TAG, "showPlaybackControl setClickListener "+JSON.toJSONString(isPlaybackPause));
            isPlaybackPause = pause;
            showPlaybackControl();
            if (playerViewClickListener != null){
                playerViewClickListener.onScreenClick();
                playerViewClickListener.onShowNav(!isPlaybackPause);
            }
            if (pause){
                playerView.pause();
            }else {
                playerView.resume();
            }
            if (onControlClickListener!=null){
                onControlClickListener.onControl(pause);
            }

        });
    }



    public void resolutionChanged() {
        if (recordTimeLayout.getVisibility() == VISIBLE) {
            MsgCenterToast.show(getContext(), R.string.camera_player_screencap);
        } else {
            List<String> list = getResolution();
            if (AppHelper.mustModify(list)){
                AppHelper.getModifyList(list);
            }
            if (playerViewClickListener != null){
                playerViewClickListener.onShowResolution(list);
                playerViewClickListener.onShowBar();
            }
        }
    }

    public void screenCapClick() {
        if (playerViewClickListener != null) {
            playerViewClickListener.onScreenCapClick();
        }

        String title =  getContext().getString(com.module.appcommon.R.string.no_permission_to_work_with_screenvideo);
        String content =  getContext().getString(com.module.appcommon.R.string.enable_permission_storage);
        PermissionUtil permissionUtil = new PermissionUtil(mContext);
        permissionUtil.checkPermissionFirst(Permission.WRITE_EXTERNAL_STORAGE, () -> {
            recordStart();
        }, title, content);
    }

    public void screenShotResult() {
        String title =  getContext().getString(com.module.appcommon.R.string.no_permission_to_work_with_screenvideo);
        String content =  getContext().getString(com.module.appcommon.R.string.enable_permission_storage);
        PermissionUtil permissionUtil = new PermissionUtil(mContext);
        permissionUtil.checkPermissionFirst(Permission.WRITE_EXTERNAL_STORAGE, () -> {
            saveBmp2Gallery();
        }, title, content);
    }

    public void switchPlayer(int current, boolean sendCMD) {
        if (deviceFeature != null) {
            deviceFeature.currentPlayer = current;
        }
        if (playerView instanceof CameraPlayerPiPVerticalView) {
            CameraPlayerPiPVerticalView v = (CameraPlayerPiPVerticalView) playerView;
            v.switchPlayer(current);
            if (playerViewClickListener != null) {
                playerViewClickListener.onSwitchPlayer(current, sendCMD);
            }
            setResolution();
        }
        showPTZ();
    }


    private void recordStart() {
        boolean isMustConvert = DeviceModelHelper.isMustConvert(deviceModelBean);
        TGLog.i(TAG, "isTransImage = " + isMustConvert + "，isPlaybackRunning = " + isPlaybackRunning + ", isHighResolution = " + isHighResolution());
        boolean scale = false;
        if (isMustConvert){
            if (isPlaybackRunning){
                scale = true;
            }else if (isHighResolution()){
                scale = true;
            }
        }

        if (scale){
            VideoFileRecorder.getInstance().setScaleVideo(true);
            VideoFileRecorder.getInstance().setScaleWitdh(MAGE_1080P_W);
            VideoFileRecorder.getInstance().setScaleHeight(MAGE_1080P_H);
        }
        if (playerView != null) {
            playerView.recordStart();
        }
    }

    public void playerHide() {
        mResetPlayer = true;
        if (playerView != null) {
            playerView.mediaSyncClear();
            playerView.playerHide();
        }
        mResetPlayer = false;
    }

    public void recordEnd() {
        if (playerView != null) {
            playerView.recordEnd();
        }
    }

    public void setDispInfo(int width, int height){
        playerView.setDispInfo(width, height);
    }


    private boolean isSwap(){
        int userId = PreferenceUtil.getInt(mContext, CommonConstants.PRE_USER_ID);
        if (deviceFeature != null){
            return ActivityHelper.getSwapScreen(mContext, deviceFeature.uuid, userId);
        }
        if (mDevice != null){
            return ActivityHelper.getSwapScreen(mContext, mDevice.uuid, userId);
        }

        return false;
    }

    private boolean isSwap(String uuid){
        if (StringUtils.isEmpty(uuid)){
            return false;
        }

        int userId = PreferenceUtil.getInt(mContext, CommonConstants.PRE_USER_ID);
        return ActivityHelper.getSwapScreen(mContext, uuid, userId);
    }


    public boolean swapScreen(DeviceFeature deviceFeature){
        if (DeviceFeatureHelper.supportMultiChannels(deviceFeature)) {
            if (playerView instanceof CameraPlayerPiPVerticalView){
                int userId = PreferenceUtil.getInt(mContext, CommonConstants.PRE_USER_ID);
                boolean isSwap = ActivityHelper.getSwapScreen(mContext, deviceFeature.uuid, userId);
                if (this.isSwapScreen != isSwap){
                    this.isSwapScreen = isSwap;
                    setDeviceFeature(deviceFeature, "swapScreen");
                    return true;
                }
            }
        }
        return false;
    }

    public void setDeviceFeature(DeviceFeature deviceFeature) {
        setDeviceFeature(deviceFeature, null);
    }

    private CameraPlayerPiPVerticalView createVerticalView(){
        CameraPlayerPiPVerticalView pVerticalView = null;
        TGLog.d(TAG, "new CameraPlayerPiPVerticalView isSwapScreen2:"  + isSwapScreen);
        if (this.isSwapScreen){
            pVerticalView = new CameraPlayerPiPSwapVerticalView(mContext);
        }else{
            pVerticalView = new CameraPlayerPiPVerticalView(mContext);
        }
        return pVerticalView;

    }

    public void setDeviceFeature(DeviceFeature deviceFeature, String from) {
        this.deviceFeature = deviceFeature;
        if (StringUtils.isEmpty(from)){
            this.isSwapScreen = isSwap();
        }
        if (deviceFeature == null) {
            playerView.setDevice(mDevice);
            return;
        }
        setSolarDeviceRecordType();
        if (toolbarView != null){
            toolbarView.showMute(deviceFeature.supportMicrophone);
        }

        if (deviceFeature.supportZoom) {
            mZoomView.parseZoomParam(deviceFeature.getZoomFeature(0));
        }
        TGLog.d(TAG, "new CameraPlayerPiPVerticalView isSwapScreen1:"  + isSwapScreen);
        if (DeviceFeatureHelper.supportMultiChannels(deviceFeature) && (!(playerView instanceof CameraPlayerPiPVerticalView) || !StringUtils.isEmpty(from))) {
            CameraPlayerPiPVerticalView pVerticalView = null;
            TGLog.d(TAG, "new CameraPlayerPiPVerticalView isSwapScreen2:"  + isSwapScreen);
            boolean isCreated = false;
            if (this.isSwapScreen){
                TGLog.d(TAG, "new CameraPlayerPiPSwapVerticalView from:"  + from);
                if (playerView instanceof CameraPlayerPiPSwapVerticalView){
                    isCreated = true;
                }else{
                    pVerticalView = new CameraPlayerPiPSwapVerticalView(mContext);
                    TGLog.d(TAG, "-- CameraPlayerPiPSwapVerticalView --");
                }
            }else{
                TGLog.d(TAG, "new CameraPlayerPiPVerticalView from:" + from);
                if (playerView instanceof CameraPlayerPiPVerticalView && !(playerView instanceof CameraPlayerPiPSwapVerticalView)){
                    isCreated = true;
                }else{
                    pVerticalView = new CameraPlayerPiPVerticalView(mContext);
                    TGLog.d(TAG, "-- CameraPlayerPiPVerticalView --");
                }
            }

            TGLog.d(TAG, "isCreated:" + isCreated);
            if (!isCreated){
                ViewGroup.LayoutParams param = playerView.getLayoutParams();
                rootView.removeView(playerView);
                boolean isOverlap = false;
                if (mDeviceUIHelper.getPlaybackDisplay() != PLAY_MODE_REALTIME){
                    isOverlap = !CameraViewHelper.supportMultiChannelsPlaybackVertical(deviceFeature,mContext);
                }
                pVerticalView.setOpenOverlap(isOverlap);
                pVerticalView.setOnCameraPlayerListener(viewId -> {
                    setLensesChanged(viewId == PLAYER_ID_MINI);
                });

                if (!isOverlap){
                    playerView.setForeSightEnable(deviceFeature.supportLocInPic);
                    pVerticalView.setForeSightSubEnable(deviceFeature.supportLocInPic2);
                }
                pVerticalView.setOnSwitchPlayerListener(this::switchPlayer);
                playerView = pVerticalView;
                TGLog.d(ZoomView.TAG, "addPlayerView pVerticalView");
                playerView.setAnchorView(rootView);
                rootView.addView(playerView, 0, param);
            }
        }else {
            playerView.setForeSightEnable(deviceFeature.supportLocInPic);
        }


        playerView.initMediaSync(DeviceTypeHelper.isLockBell(mDevice.device_type));
        if (DeviceFeatureHelper.supportMultiChannels(deviceFeature) && playerView instanceof CameraPlayerPiPVerticalView) {
            ((CameraPlayerPiPVerticalView)playerView).parseZoomParam(deviceFeature.getZoomFeature(0));
            ((CameraPlayerPiPVerticalView)playerView).parseZoomParam(deviceFeature.getZoomFeature(1));
        }

        TGLog.d(TAG, "CameraPlayerPiPVerticalView mFloatView = " + mFloatView);
        playerView.setAnchorView(rootView);
        playerView.setFloatView(mFloatView);
        updateListener();
        playerView.setDeviceFeature(deviceFeature);
        playerView.setDevice(mDevice);
        playerView.setLiveViewShow(isLiveViewShow);
        playerView.setUpdateViewSizeEnable(isUpdateViewSizeEnable);
        toolbarView.setDeviceFeature(deviceFeature);

        initDeviceInfo();

    }

    private void updateListener() {
        playerView.setOnMediaPlayListener(onMediaPlayListener);
        playerView.setOnScreencapListener(onScreencapListener);
        playerView.setFormatChangedListener(formatChangedListener);
        playerView.setOnZoomViewListener(onMainZoomViewListener);
        playerView.setResetListener(() -> TGThreadPool.executeOnUiThread(this::playerHide));
        playerView.setForeSightListener(onPlayerForeSightListener);
        if (DeviceFeatureHelper.supportPTZ(deviceFeature)) {
            if (AppUtil.isLandscape(getContext())) {
                playerView.setPtzControlTouchListener(ptzControlTouchListener);
            } else {
                if (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME) {
                    playerView.setPtzControlTouchListener(ptzControlTouchListener);
                } else {
                    playerView.setPtzControlTouchListener(null);
                }
            }
        } else {
            playerView.setPtzControlTouchListener(null);
        }
    }

    public void setSolarDeviceRecordType(){
        if (DeviceHelper.isSolar(mDevice)){
            Box<DeviceSettingsInfo> settingsInfoBox = ObjectBoxUtil.getDeviceSettingsInfo();
            if (settingsInfoBox != null) {
                DeviceSettingsInfo deviceSettingsInfo = settingsInfoBox.query().equal(DeviceSettingsInfo_.uuid, mDevice.uuid).build().findFirst();
                if (deviceSettingsInfo != null){
                    mSolarBatteryView.setRecordType(deviceSettingsInfo.recordType);
                }
            }
        }
    }

    public void receiveVideoData(AVFrames avFrame) {
        if (playerView != null && !mResetPlayer) {
            playerView.receiveVideoData(avFrame);
        }
    }

    public void receiveVideoMiniData(AVFrames avFrame) {
        if (playerView != null && !mResetPlayer) {
            playerView.receiveVideoMiniData(avFrame);
        }
    }

    public void receiveAudioData(AVFrames avFrame) {
        if (!isMuteOn && !mResetPlayer) {
            if (playerView != null) {
                playerView.receiveAudioData(avFrame);
            }
        }

    }

    @Override

    public void onClick(View view) {
        if (playerViewClickListener == null) return;
        playerViewClickListener.onScreenClick();
        int viewId = view.getId();
        if (viewId == R.id.ll_camera_player_record_time) {
            TGLog.d(TAG, "click recordEnd");
            recordEnd();
            screenSaveEnd();
        }
    }

    public int getIndex(){
        return QualityUIHelper.getIndex(deviceFeature, mResolution);
    }

    private List<String> getResolution() {
        String current;
        String[] newArr = getResources().getStringArray(R.array.camera_live_resolution);
        List<String> list = Arrays.asList(newArr);
        Collections.reverse(list);
        if (mResolution == AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN) {
            current = newArr[1];
        } else {
            current = newArr[0];
        }
        if (deviceFeature != null && deviceFeature.getSupportResolutions() != null) {
            list = QualityUIHelper.getQualitys(deviceFeature);
            current = QualityUIHelper.getQualityType(deviceFeature, mResolution);
        }
        List<String> data = new ArrayList<>();
        data.add(current);
        data.addAll(list);
        return data;
    }

    public boolean isHighResolution(){
        List<String> list = getResolution();
        if (list.size() > 2){
            String cur = list.get(0);
            String first = list.get(1);
            return StringUtils.equalsIgnoreCase(cur, first);
        }
        return false;
    }

    public void onSelectResolutionClick(String text, int index) {
        List<String> list = getResolution();
        if (AppHelper.mustModify(list)){
            AppHelper.getModifyList(list);
        }

        int count = 0;
        for (int i = 1; i < list.size(); i++) {
            if (text.equals(list.get(i))) {
                count++;
            }
        }
        if (count > 1 && index != -1){
            onClickSelectResolution(list, index);
        }else{
            for (int i = 1; i < list.size(); i++) {
                if (text.equals(list.get(i))) {
                    onClickSelectResolution(list, i - 1);
                    break;
                }
            }
        }
    }

    public void onSelectSpeedClick(String text) {
        List<String> list = getSpeed();
        for (int i = 1; i < list.size(); i++) {
            if (text.equals(list.get(i))) {
                int speed = 1 << (i - 1);
                toolbarView.setSpeedIcon(String.valueOf(speed));
                if (playerViewClickListener != null) {
                    playerViewClickListener.onSpeedClick(speed);
                }
                break;
            }
        }
    }

    private List<String> getSpeed() {
        String current = toolbarView.getSpeedDescription();
        String[] newArr;
        String[] array = getResources().getStringArray(R.array.playback_speeds);
        newArr = array;
        if (cameraType == CommonConstants.CAMERA_TYPE_PLAYBACK_SDCARD) {
            newArr = Arrays.copyOf(array, 3);
        }
        String[] finalNewArr = newArr;
        switch (current) {
            case CameraPlayerToolbarView.SPEED_2:
                current = finalNewArr[1];
                break;
            case CameraPlayerToolbarView.SPEED_4:
                current = finalNewArr[2];
                break;
            case CameraPlayerToolbarView.SPEED_8:
                if (finalNewArr.length > 3) {
                    current = finalNewArr[3];
                }
                break;
            default:
                current = finalNewArr[0];
        }

        List<String> list = new ArrayList<>();
        list.add(current);
        list.addAll(Arrays.asList(finalNewArr));
        return list;
    }

    public void updatePlaybackControl(){

        TGThreadPool.executeOnUiThread(() -> {
            isPlaybackPause = false;
            if (isToolbarhide){
                playBackControlView.setVisibility(GONE);
                return;
            }
            if (toolbarView.getVisibility()==VISIBLE&&playBackControlView.getVisibility()==GONE){
                showPlaybackControl();
            }
        });


    }
    private void showPlaybackControl(){
        if (isLiveVideoPlay())return;
        TGLog.i(TAG, "showPlaybackControl "+JSON.toJSONString(isPlaybackPause));
        if (isPlaybackPause){
            playBackControlView.showResume();
            toolbarView.setScreenCapDisable();
        }else {
            playBackControlView.showPause();
            toolbarView.setScreenCapEnable();
        }
    }

    public void onClickSelectResolution(List<String> list, int position) {
        int resloution = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MAX;
        String data = list.get(position + 1);
        boolean isSupport = deviceFeature != null && deviceFeature.getSupportResolutions() != null;

        if (isSupport) {
            resloution = deviceFeature.getQualityTypeIndex(position);
        } else {
            if (AppHelper.mustModify(list)){
                if (StringUtils.equals(getResources().getString(R.string.high_definition), data)){
                    data = getResources().getString(R.string.normal_definition);
                } else if (StringUtils.equals(getResources().getString(R.string.full_high_definition), data)){
                    data = getResources().getString(R.string.high_definition);
                }
            }

            if (AppHelper.isQmsyApp()){
                if (TextUtils.equals(getResources().getString(R.string.high_definition), data)) {
                    resloution = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
                }
            }else{
                if (TextUtils.equals(getResources().getString(R.string.normal_definition), data)) {
                    resloution = AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN;
                }
            }
        }

        setResolution(resloution);
        playerViewClickListener.onResolutionChanged(playerView.getCurrentPlayer(), resloution);
    }

    public void setSimServicePayBannerShow(){
        if (DeviceItemHelper.is4GDeviceWithSimCard(mDevice)&&mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME&&!isLandscape()){
            simServicePayBanner.updateView(mDevice);
            int bannerTop = DimenUtil.dp2px(mContext,40);
            int height = (int) (getHeight()-getResources().getDimension(R.dimen.player_height)/2-bannerTop);
            if (height>0){
                ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) simServicePayBanner.getLayoutParams();
                layoutParams.topMargin = height>bannerTop?bannerTop:height;
                simServicePayBanner.setLayoutParams(layoutParams);
            }
        }else{
            simServicePayBanner.setVisibility(GONE);
        }
    }
    public void onOrientationChanged(int o, boolean isShowPlayback, boolean isPlayback) {
        initZoomLenses();
        initFocusView();
        setUpdateViewSize(true);
        setZoomHidden();
        TGLog.i(TAG, "onOrientationChanged");

        toolbarView.onOrientationChanged(o, isShowPlayback);
        if (o == Configuration.ORIENTATION_PORTRAIT) {
            mPlayBackTimeLine.setVisibility(GONE);
            int dp10 = DimenUtil.dp2px(mContext, 10);
            toolbarView.setPadding(dp10, 0,dp10, toolbarView.getPaddingBottom());
            if (isShowPlayback) {
                toolbarView.setPlayback(isPlayback);
            }
            if (!DeviceFeatureHelper.supportMultiChannels(deviceFeature)) {
                toolbarView.hidePTZ();
            }
            setSimServicePayBannerShow();

        } else {
            ConstraintLayout.LayoutParams toolbarParams = (ConstraintLayout.LayoutParams) toolbarView.getLayoutParams();
            toolbarParams.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
            toolbarParams.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
            toolbarParams.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
            int dp30 = DimenUtil.dp2px(mContext, 30);
            toolbarView.setPadding(dp30, 0, dp30, toolbarView.getPaddingBottom());
            mPlayBackTimeLine.setPadding(dp30,0, dp30, toolbarView.getPaddingBottom());
            toolbarView.setLayoutParams(toolbarParams);

            if (isLiveVideoPlay()) {
                if (deviceFeature != null && deviceFeature.supportSpeaker) {
                    toolbarView.supportSpeaker();
                }

                if (DeviceFeatureHelper.supportPTZ(deviceFeature)) {
                    toolbarView.supportPTZ();
                }
            }
            simServicePayBanner.setVisibility(GONE);
        }
    }

    private boolean isLandscape(){
        return getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE;
    }
    public void showControlBtn(boolean isPlayback) {
        if (isLiveVideoPlay() && DeviceFeatureHelper.supportMultiChannelsPtz(deviceFeature) &&  isLandscape()) {
            isPlayback = false;
        }
        if (isPlayback) {
            toolbarView.setPlayback(true);
        } else if (deviceFeature != null) {
            if (DeviceFeatureHelper.supportPTZ(deviceFeature)) {
                if (isLandscape()){
                    toolbarView.supportPTZ();
                }else {
                    toolbarView.hidePTZ();
                }
            }
            if (deviceFeature.supportSpeaker&&isLiveVideoPlay()&&isLandscape()) {
                toolbarView.supportSpeaker();
            }
        }
    }

    public void setOnCameraZoomListener(OnCameraZoomListener onCameraZoomListener) {
        this.onCameraZoomListener = onCameraZoomListener;
    }

    public void initFocusView(){
        if (DeviceFeatureHelper.supportFocus(deviceFeature)) {
            setFocusingView(VISIBLE, false);
        } else {
            setFocusingView(GONE, false);
        }
    }

    public void initZoomLenses() {
        if (deviceFeature != null) {
            TGLog.d(ZoomView.TAG, "deviceFeature =" + deviceFeature + ", zoomPos = " + zoomPos + ", deviceFeature.supportZoom = " + deviceFeature.supportZoom + ",deviceFeature.support2Lenses=" + deviceFeature.support2Lenses);
        }

        if (zoomPos >= 0 && deviceFeature != null) {
            if (deviceFeature.supportZoom) {
                mZoomView.setOnCameraZoomListener(onCameraZoomListener);
                mZoomView.initZoom(deviceFeature.getZoomFeature(0));
                mZoomView.setZoomFactor(zoomPos);
                mLensesGroup.setVisibility(GONE);
                setZoomView(VISIBLE);
            } else {
                HideZoomView(mZoomView, mZoomTextView);
            }

            if (DeviceFeatureHelper.supportMultiChannels(deviceFeature)) {
                mLensesGroup.setVisibility(GONE);
                if (playerView instanceof CameraPlayerPiPVerticalView){
                    mZoomView.setVisibility(GONE);
                    ((CameraPlayerPiPVerticalView)playerView).setOnCameraZoomListener(onCameraZoomListener, 0);
                    ((CameraPlayerPiPVerticalView)playerView).setOnCameraZoomListener(onCameraZoomListener, 1);
                    ((CameraPlayerPiPVerticalView)playerView).initZoom(deviceFeature.getZoomFeature(0), 0);
                    ((CameraPlayerPiPVerticalView)playerView).initZoom(deviceFeature.getZoomFeature(1), 1);
                    ((CameraPlayerPiPVerticalView)playerView).setZoomFactor(zoomPos, 0);
                    ((CameraPlayerPiPVerticalView)playerView).setZoomFactor(zoomPos2, 1);
                    if (deviceFeature.getZoomFeature(0) != null){
                        TGLog.d(ZoomView.TAG, "startAnalogZoom = " + deviceFeature.getZoomFeature(0).startAnalogZoom);
                        if (deviceFeature.getZoomFeature(0).startAnalogZoom) {
                            analogZoom(zoomPos, 0, false, 0, ZOOM_INIT);
                        }
                    }
                    if (deviceFeature.getZoomFeature(1) != null){
                        TGLog.d(ZoomView.TAG, "startAnalogZoom1 = " + deviceFeature.getZoomFeature(1).startAnalogZoom);
                        if (deviceFeature.getZoomFeature(1).startAnalogZoom) {
                            analogZoom(zoomPos2, 0, false, 1, ZOOM_INIT);
                        }
                    }
                }

            } else {
                if (deviceFeature.support2Lenses) {
                    setLensesType(zoomPos);
                    if (toolbarView.getVisibility() == VISIBLE && isLiveVideoPlay() && !deviceFeature.noShortcut) {
                        mLensesGroup.setVisibility(VISIBLE);
                    }
                }
            }
            if (isLiveViewShow) {
                supportMultiChannelsPTZ();
            }
        }
    }

    private void supportMultiChannelsPTZ() {
        if (DeviceFeatureHelper.supportMultiChannelsPtz(deviceFeature) && DeviceFeatureHelper.supportPTZ(deviceFeature)) {
            toolbarView.supportPTZ();
        }
    }

    public void updateZoomLenses(float zoomPos, int channel) {
        TGLog.d(ZoomView.TAG, "zoomPos = " + zoomPos + ", channel = " + channel);
        if (channel == 0){
            this.zoomPos = zoomPos;
            if (deviceFeature != null) {
                deviceFeature.zoomPos = zoomPos;
            }
        }else {
            this.zoomPos2 = zoomPos;
            if (deviceFeature != null) {
                deviceFeature.zoomPos2 = zoomPos;
            }
        }
        if (DeviceFeatureHelper.supportMultiChannels(deviceFeature) && playerView instanceof CameraPlayerPiPVerticalView){
            ((CameraPlayerPiPVerticalView)playerView).setZoomFactor(zoomPos, channel);
        }else{
            mZoomView.setZoomFactor(zoomPos);
            setLensesType(zoomPos);
        }


    }
    private boolean is2LensesCapZoomFar(){
        if (deviceFeature.is2LensesCapZoom() && !deviceFeature.supportMultiChannels && deviceFeature.getZoomFeature(0).zoomDivider > 0 && this.zoomPos >= deviceFeature.getZoomFeature(0).zoomDivider){
            return  true;
        }
        return false;
    }

    public void setPrimaryView(int pos) {
        if (pos == 1) {
            mLensesFar.setChecked(true);
        } else {
            mLensesNear.setChecked(true);
        }
    }

    public void showPTZ() {
        if (DeviceFeatureHelper.supportPTZ(deviceFeature)) {
            if (AppUtil.isLandscape(getContext())) {
                playerView.setPtzControlTouchListener(ptzControlTouchListener);
                if (isLiveVideoPlay()){
                    toolbarView.supportPTZ();
                }else{
                    toolbarView.hidePTZ();
                }
            } else {
                if (mDeviceUIHelper.getPlaybackDisplay() == PLAY_MODE_REALTIME) {
                    playerView.setPtzControlTouchListener(ptzControlTouchListener);
                    toolbarView.supportPTZ();
                } else {
                    playerView.setPtzControlTouchListener(null);
                    toolbarView.hidePTZ();
                }
            }
        } else {
            playerView.setPtzControlTouchListener(null);
            toolbarView.hidePTZ();
            if (AppUtil.isLandscape(getContext())) {
                if (playerViewClickListener != null) {
                    playerViewClickListener.setPtzControlViewVisible(false);
                }
            }
        }
    }

    public void setSpeed(int speed) {
        if (playerView != null) {
            playerView.setSpeed(speed);
        }
        toolbarView.setSpeedIcon(String.valueOf(speed));
    }

    public void setResolution(int resolution) {
        mResolution = resolution;
        List<String> list = deviceFeature != null? deviceFeature.getSupportResolutions() : new ArrayList<>();
        if (deviceFeature != null) {
            int resID = QualityUIHelper.getQualityResId(deviceFeature, resolution);
            if (resID > 0) {
                if (AppHelper.mustModify(list) && AppHelper.isQmsyApp()){

                    if (resID == R.mipmap.icon_camera_player_sd){
                        resID = R.mipmap.icon_camera_player_hd;
                    }else if (resID == R.mipmap.icon_camera_player_hd){
                        resID = R.mipmap.icon_camera_player_fhd;
                    }else if (resID == R.mipmap.icon_camera_player_fhd){
                        if (list.size() == 3){
                            if (StringUtils.equalsIgnoreCase(list.get(0), "fhd")){
                                resID = R.mipmap.icon_camera_player_uhd;
                            }
                        }
                    }


                }
                toolbarView.setResolutionImageResource(resID);
            }
        } else {
            if (mResolution == AVIOCTRLDEFs.AVIOCTRL_QUALITY_MIN) {
                if (AppHelper.mustModify(list) || AppHelper.isQmsyApp()){
                    toolbarView.setResolutionImageResource(R.mipmap.icon_camera_player_hd);
                }else{
                    toolbarView.setResolutionImageResource(R.mipmap.icon_camera_player_sd);
                }

            } else {
                if (AppHelper.mustModify(list) || AppHelper.isQmsyApp()){
                    toolbarView.setResolutionImageResource(R.mipmap.icon_camera_player_fhd);
                }else{
                    toolbarView.setResolutionImageResource(R.mipmap.icon_camera_player_hd);
                }
            }
        }
    }

    public void recordingUpdate(long duration) {
        int time = (int) (duration / 1000);
        String timeStr = DateUtil.formatTimeHHmmss(time);
        timeStr = timeStr.substring(3);
        recordTimeText.setText(timeStr);
        if (recordTimeLayout.getVisibility() == GONE) {
            TGLog.d(TAG, "click recordingUpdate");
            TGLog.trace(TAG);
            recordTimeLayout.setVisibility(VISIBLE);
        }
    }

    public void screenSaveEnd() {
        TGLog.d(TAG, "click screenSaveEnd");
        recordTimeLayout.setVisibility(GONE);
        toolbarView.screenSaveEnd();
    }

    public void screenSaveLocal() {
        Bitmap bmp = getTextureViewBmp();
        if (bmp != null && mDevice != null) {
            int pixel = bmp.getPixel(0,0);
            int pixel20 = bmp.getPixel(20,20);
            if (pixel==pixel20&&pixel==0){
                return;
            }
            LocalThumbnailUtils.getInstance().saveLocalThumbnail(bmp, mDevice.uuid);
        }
    }

    public Bitmap getTextureViewBmp() {
        return playerView.getTextureViewBmp();
    }

    public void saveBmp2Gallery() {

        Bitmap bmp = getTextureViewBmp();
        if (bmp == null) {
            return;
        }

        if (DeviceModelHelper.isMustConvert(deviceModelBean)){
            if (this.isPlaybackRunning){
                bmp = AbImageUtil.getScaleBitmap(bmp, MAGE_1080P_W, MAGE_1080P_H, false);
            }else if (isHighResolution()){
                bmp = AbImageUtil.getScaleBitmap(bmp, MAGE_1080P_W, MAGE_1080P_H, false);
            }
        }

        int ret = ImageUtils.saveFile(mContext, bmp);
        if (ret == 0) {
            screenSaveEnd();
            showThumbnail(bmp);
            if (playerViewClickListener != null){
                playerViewClickListener.onScreenShotResult(true);
            }

            return;
        }

        screenSaveEnd();
        if (playerViewClickListener != null){
            playerViewClickListener.onScreenShotResult(false);
        }
    }

    public void setLiveViewShow(boolean islive) {
        isLiveViewShow = islive;
        if (playerView != null) {
            if (playerView instanceof CameraPlayerPiPVerticalView){
                CameraPlayerPiPVerticalView pVerticalView = (CameraPlayerPiPVerticalView) playerView;
                boolean overlap = false;
                if (!islive){
                    overlap = !CameraViewHelper.supportMultiChannelsPlaybackVertical(deviceFeature,getContext());
                }
                pVerticalView.setOpenOverlap(overlap);
            }
            playerView.setLiveViewShow(isLiveViewShow);
        }
        if (islive) {
            supportMultiChannelsPTZ();
        }else {
            simServicePayBanner.setVisibility(GONE);
        }

    }

    public void hideThumbnail() {
        thumbnailLayout.setVisibility(View.GONE);
    }

    public void showThumbnail(Bitmap bmp) {
        if (bmp != null) {
            Bitmap bitmap = getBitmap(bmp,DimenUtil.dp2px(mContext,86),DimenUtil.dp2px(mContext,50));
            thumbnailImage.setImageBitmap(bitmap);
            thumbnailLayout.setVisibility(View.VISIBLE);
            LogUtils.matTrackCustomKVEvent(getContext(), "live_play", "LPJ");
        }
    }

    public static Bitmap getBitmap(Bitmap bitmap, int targetWidth,
                                   int targetHeight) {
        int srcWidth = bitmap.getWidth();
        int srcHeight = bitmap.getHeight();
        float widthScale = targetWidth * 1.0f / srcWidth;
        float heightScale = targetHeight * 1.0f / srcHeight;
        Matrix matrix = new Matrix();
        matrix.postScale(widthScale, heightScale, 0, 0);
        // 如需要可自行设置 Bitmap.Config.RGB_8888 等等
        Bitmap bmpRet = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bmpRet);
        Paint paint = new Paint();
        canvas.drawBitmap(bitmap, matrix, paint);
        return bmpRet;
    }
    public void setDateLine(String dateLine) {
        toolbarView.setDateLine(dateLine);
    }

    public void playbackResetMin() {
        if (playerView != null) {
            playerView.playbackResetMin();
        }
    }
    public void setOnAudioAecmListener(AudioDecoder.OnAudioAecmListener listener){
        if (playerView!=null){
            playerView.setOnAudioAecmListener(listener);
        }
    }
    public void addRecord(byte[] data){
        if (playerView!=null){
            playerView.addRecord(data);
        }
    }

    public void switchPlayerHide() {
        if (playerView != null) {
            playerView.switchPlayerHide();
        }
    }

    public void updateView() {
        if (playerView != null) {
            playerView.updateView();
        }
    }

    public void analogZoom(float scale,int duration, boolean isClick, int index, String from) {
        if (playerView != null) {
            DeviceFeature.ZoomFeature zoomFeature = deviceFeature.getZoomFeature(index);
            boolean isNear = mLensesNear.isChecked();

            float overScaleStart = 1;
            float overScaleEnd = 1;
            boolean animation = false;
            float startF = (zoomFeature.startFactor - 1) / zoomFeature.analogMultiple;
            TGLog.d(ZoomView.TAG, "startF = " + startF + ", zoomFeature.isAnalogZoom(scale) = " + zoomFeature.isAnalogZoom(scale) + ", zoomFeature.isSingleZoom() =" + zoomFeature.isSingleZoom());
            boolean isOverDivider = scale > zoomFeature.zoomDivider;
            if (zoomFeature.isAnalogZoom(scale)) {
                if (zoomFeature.isSingleZoom()){
                    float progress = scale * startF + 1.0f;
                    scale = new BigDecimal(progress).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                    animation = true;
                }else {
                    if (isClick) {
                        scale = 1;
                        isNear = false;
                    } else {
                        animation = true;
                        float progress = scale * startF + 1.0f;
                        if (isOverDivider) {
                            progress = scale* zoomFeature.maxFactor;
                            scale = new BigDecimal(progress).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                            progress = scale / zoomFeature.startFactor;
                            TGLog.d(TAG, "analogZoom 1 : " + progress);
                        } else {
                            isNear = !isNear;
                        }
                        scale = new BigDecimal(progress).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                    }
                    if (isNear) {
                        float overScale = zoomFeature.zoomDivider * startF + 1.0f;
                        overScale = new BigDecimal(overScale).setScale(1, BigDecimal.ROUND_HALF_UP).floatValue();
                        if (isOverDivider) {
                            overScaleStart = overScale;
                        } else {
                            overScaleEnd = overScale;
                        }
                        TGLog.d(TAG, "analogZoom " + scale + " overScaleStart: " + overScaleStart + " overScaleEnd: " + overScaleEnd);
                        playerView.analogOverZoom(overScaleStart, overScaleEnd,duration, index);
                    }
                }
                TGLog.d(ZoomView.TAG, "analogZoom " + scale + " animation: " + JSON.toJSONString(animation) + " index: " + index + ", duration = " + duration);
                playerView.analogZoom(scale, animation,duration, index, from);
            }
        }
    }

    public void audioReset() {
        if (playerView!=null){
            playerView.audioReset();
        }
    }

    public interface ACCameraPlayerViewClickListener {
        void onMuteOnClick();

        void setPtzControlViewVisible(boolean show);

        void onReconnectClick();

        void onDeviceOpenClick();

        void onPtzControlClick();

        void onPlayBackControlClick();

        void onLensesChanged(int type,boolean isClicked);

        void onSpeedClick(int type);

        void onResolutionChanged(int channel, int resolution);

        void onShowResolution(List<String> list);

        void onShowSpeed(List<String> list);


        void onScreenShotResult(boolean succeed);

        void onScreenFullClick();

        void onShowBar();

        void onMicphoneLandClick();

        void onShowNav(boolean isClick);

        void onSwitchPlayer(int currentPlayer, boolean sendCMD);

        void onWifiSettings();

        void onOpenServe();

        void onScreenCapClick();

        void onScreenClick();
        void onHelpClick(boolean isbad);
        void onAdjustHeight();
    }
}
